package com.huilian.iotbox.data.service.impl;

import com.huilian.iotbox.data.common.RedisKey;
import com.huilian.iotbox.data.dao.SystemMerchantConfigDao;
import com.huilian.iotbox.data.service.SystemMerchantConfigSerivce;
import com.huilian.iotbox.data.po.SystemMerchantConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author lizhiquan
 * @CreateDate: 2021-04-01-22-15
 * @Description:
 */
@Service
public class SystemMerchantConfigSerivceImpl implements SystemMerchantConfigSerivce {

    @Resource
    private SystemMerchantConfigDao systemMerchantConfigDao;
    @Resource
    private RedisTemplate<String, Serializable> redisCacheTemplate;

    @Override
    public SystemMerchantConfig findSystemMerchant() {
        final String key = RedisKey.SYSTEM_MERCHANT_LIST;
        List<SystemMerchantConfig> systemMerchantConfigList = (List<SystemMerchantConfig>) redisCacheTemplate.opsForValue().get(key);
        SystemMerchantConfig systemMerchantConfig = null;
        if (systemMerchantConfigList == null) {
            systemMerchantConfigList = systemMerchantConfigDao.findSystemMerchant();
            redisCacheTemplate.opsForValue().set(key, (Serializable) systemMerchantConfigList, 30, TimeUnit.DAYS);
        }

        if (systemMerchantConfigList.size() > 0) {
            int index = (int) (Math.random() * systemMerchantConfigList.size());
            systemMerchantConfig = systemMerchantConfigList.get(index);
        }
        return systemMerchantConfig;
    }
}
